package com.roc.service.impl.term;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.Operators;
import com.roc.pojo.TermVer;
import com.roc.service.ServiceException;
import com.roc.service.impl.ReviseMerinfoServiceImpl;
import com.roc.service.term.TermVerService;
import com.roc.util.Constance;
import com.roc.util.constant.SysLogType;
@Service
@Transactional
public class TermVerServiceImpl implements TermVerService{
	
	@Autowired
	private IBaseDao baseDao;
	@Autowired
	private IPageDao pageDao;
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	
	static Logger logger=Logger.getLogger(TermVerServiceImpl.class);
	
	
	
	@Override
	public boolean isExistName(TermVer termVer) throws ServiceException {
		// TODO Auto-generated method stub
		StringBuffer sql =new StringBuffer();
		sql.append(" SELECT count(1) FROM  t_term_ver  t WHERE   t.manufacturer=? AND  t.model_id =?  AND t.version_id =? ");
		List<Object> params = new ArrayList<Object>();
		params.add(termVer.getManufacturer());
		params.add(termVer.getModelId());
		params.add(termVer.getVersionId());
		
		if(termVer.getId()!=0){
			sql.append(" and T.ID!=? ");
			params.add(termVer.getId());
		}
		try {
			List<Object> list = sqlBaseDao.queryAll(sql.toString(), params.toArray());
			if (list != null && !list.isEmpty()) {
				BigDecimal result = (BigDecimal) list.get(0);
				if (result.intValue() > 0)
					return false;
			}
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
	}
	
	
	
	/**
	 * 添加
	 */
	@Override
	public Map<String, Object> insertTermVerManage(TermVer termVer,Operators op) throws ServiceException {
		Map<String,Object> resultMap=new LinkedHashMap<String, Object>();
		List<Object> queryManufacturerList=null;
		List<Object> queryModelIdList=null;
		try {
			//查询数据库表中是否存在该版本数据 存在测返回 
			String queryExistSql="SELECT count(1) FROM T_TERM_VER t   where  t.MANUFACTURER=?  and t.MODEL_ID=?  and t.VERSION_ID=?";
			
			Object[] param={termVer.getManufacturer(),termVer.getModelId(),termVer.getVersionId()};
			List<Object> queryExistList = pageDao.querySqlAll(queryExistSql, param);
			int queryExist=Integer.valueOf(String.valueOf(queryExistList.get(0)));
			//int queryExist=(int)queryExistList.get(0);
			
			if(queryExist>0){
				resultMap.put("result","失败！此厂商型号的版本号已存在！");
				return resultMap;
			}
			
			queryManufacturerList=queryManufacturer(termVer);
			if(queryManufacturerList==null || queryManufacturerList.isEmpty()){
				//不存在该厂商  
				String maxDic_Code=queryMaxDic_Code(termVer);
				insertManufacturer(termVer,maxDic_Code);
				insertModelId(termVer,maxDic_Code,queryManufacturerList);
				insertTermVer(termVer,op);
			}else{
				//存在该厂商 查询是否存在该型号
				queryModelIdList=queryModelId(termVer,queryManufacturerList);
				if(queryModelIdList.get(0)==null || queryModelIdList.get(0).equals("")){
					//不存在该型号
					//查询该厂商最大的DIC_CODE
					String maxDic_Code=queryMaxDicCode(queryManufacturerList);
					insertModelId2(termVer,maxDic_Code,queryManufacturerList);
					insertTermVer(termVer,op);
				}else{
					//存在该型号
					insertTermVer(termVer,op);
				}
			}
			baseDao.addSyslog(SysLogType.ADD_TERMVER.getCode(), SysLogType.ADD_TERMVER.getName(), op.getAccountNo(), "操作员【"+op.getAccountNo()+"】"+"添加终端管理【厂商："+termVer.getManufacturer()+"】【型号："+termVer.getModelId()+"】【版本号："+termVer.getVersionId()+"】成功!");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.info("添加终端版本管理失败！");
			resultMap.put("result","添加终端版本管理失败");
			return resultMap;
		}
		logger.info("添加终端版本管理成功！");
		resultMap.put("result","添加终端版本管理成功！");
		return resultMap;
	}
	
	/**
	 * 根据id查询终端信息
	 * @throws DaoException 
	 */
	@Override
	public TermVer updateTermVerById(long i) throws DaoException{
		String querySql="select ID,MANUFACTURER,MODEL_ID,VERSION_ID,ISSUE_TS,IS_VALID from T_TERM_VER where id = ?";
		
		Object[] param={i};
		List<Object> queryList  =pageDao.querySqlAll(querySql, param);
		TermVer tvm=new TermVer();
		if(queryList!=null&&queryList.size()>0)
		{
			Iterator<?> iterator=queryList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				
				tvm.setId(Integer.valueOf(String.valueOf(Constance.Null2EmptyTrim(obj[0]))));
				tvm.setManufacturer(Constance.Null2EmptyTrim(obj[1]));
				tvm.setModelId(Constance.Null2EmptyTrim(obj[2]));
				tvm.setVersionId(Constance.Null2EmptyTrim(obj[3]));
				tvm.setIssueTs(Constance.Null2EmptyTrim(obj[4]));
				String state=Constance.Null2EmptyTrim(obj[5]);
				if(state.equals("0")){
					state="无效";
				}else if(state.equals("1")){
					state="有效";
				}
				tvm.setIsValId(state);//是否有效
				 i++;
			}
			return tvm;
		}return null;
	}
	

	/**
	 * 修改
	 */
	@Override
	public Map<String, Object> updateTermVerManage(TermVer termVer,Operators op) throws ServiceException {
		Map<String,Object> resultMap=new LinkedHashMap<String, Object>();
		try {
			updateTermVer(termVer,op);
			baseDao.addSyslog(SysLogType.UPDATE_TERMVER.getCode(), SysLogType.UPDATE_TERMVER.getName(), op.getAccountNo(), "操作员【"+op.getAccountNo()+"】"+"修改id为【"+termVer.getId()+"】的终端成功!");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.info("更改终端版本管理失败！");
			resultMap.put("result","更改终端版本管理失败。。。。");
			return resultMap;
		}
		logger.info("更改终端版本管理成功！");
		resultMap.put("result","更改终端版本管理成功！");
		return resultMap;
	}

	
	/**
	 * 删除
	 */
	@Override
	public Map<String, Object> deleteTermVerManage(TermVer termVer,Operators op) throws ServiceException {
		Map<String,Object> resultMap=new LinkedHashMap<String, Object>();
		try {
			deleteTermVer(termVer);
			baseDao.addSyslog(SysLogType.DELETE_TERMVER.getCode(), SysLogType.DELETE_TERMVER.getName(), op.getAccountNo(), "操作员【"+op.getAccountNo()+"】"+"删除终端管理【厂商："+termVer.getManufacturer()+"】【型号："+termVer.getModelId()+"】【版本号："+termVer.getVersionId()+"】成功!");
		} catch (DaoException e) {
			e.printStackTrace();
			logger.info("删除终端管理失败！");
			resultMap.put("result","由于某些未知的原因,程序崩溃了！请联系技术人员！/(ㄒoㄒ)/~~");
			return resultMap;
		}
		logger.info("删除终端管理成功！");
		resultMap.put("result","删除终端管理成功！");
		return resultMap;
	}

	
	
	
	
	
	

	/**
	 * 查询该厂商是否存在
	 * @param termVer
	 * @throws DaoException 
	 */
	private List<Object> queryManufacturer(TermVer termVer) throws DaoException {
		String querySql="SELECT DIC_CODE FROM TBL_DICTIONARYITEM  WHERE DIC_TYPE = 'TMNL_BRAND' and substr(dic_name,INSTR(dic_name,'_',-1)+1)=? ";
		
		Object[] param={termVer.getManufacturer()};
		List<Object> queryList = pageDao.querySqlAll(querySql, param);
		return queryList;//存在
	}
	
	
	/**
	 * 查询不存在该厂商时Dic_Code的最大值
	 * @param termVer
	 * @throws DaoException 
	 */
	private String queryMaxDic_Code(TermVer termVer) throws DaoException {
		String querySql="SELECT MAX(DIC_CODE) FROM TBL_DICTIONARYITEM  WHERE DIC_TYPE = 'TMNL_BRAND' ";
		
		List<Object> queryList = pageDao.querySqlAll(querySql, null);
		String maxDic_Code=String.valueOf(queryList.get(0));
		return maxDic_Code;
	}
	
	/**
	 * 添加新的厂商
	 * @param termVer
	 * @param maxDic_Code
	 * @throws DaoException
	 */

	private void insertManufacturer(TermVer termVer, String maxDic_Code) throws DaoException {
		String insertSql="insert into TBL_DICTIONARYITEM values(?,?,?,?,?,?)";
		
		String dicType="TMNL_BRAND";
		String dicCode=String.valueOf((Integer.valueOf(maxDic_Code)+1));
		String dicName=dicCode+"_"+termVer.getManufacturer();
		String dispOrder=String.valueOf((Integer.valueOf(maxDic_Code)+1));
		Date updateTime=new Date();
		String memo="终端型号";
		
		List<Object> list=new ArrayList<Object>();
		list.add(dicType);
		list.add(dicCode);
		list.add(dicName);
		list.add(dispOrder);
		list.add(updateTime);
		list.add(memo);
		sqlBaseDao.deleteBySql(insertSql, list);
		
	}

	
	/**
	 * 查询是否存在该型号
	 * @param termVer
	 * @return
	 * @throws DaoException 
	 */
	private List<Object> queryModelId(TermVer termVer,List<Object> queryManufacturerList) throws DaoException {
		String querySql="SELECT max(DISP_ORDER) FROM TBL_DICTIONARYLAYERITEM T  WHERE DIC_TYPE = 'TMNL_MODEL_NO' and name=? and DIC_PCODE=? ";
		Object[] param={termVer.getModelId(),queryManufacturerList.get(0)};
		List<Object> querylist = pageDao.querySqlAll(querySql, param);
		return querylist;
	}
	
	
	/**
	 *  添加在厂商的型号
	 * @param termVer
	 * @throws DaoException 
	 */
	private void insertModelId(TermVer termVer,String maxDic_Code ,List<Object> queryManufacturerList) throws DaoException {
		//List<Object> dicCodeList = loopList(queryManufacturerList);
		String dicCode0=String.valueOf((Integer.valueOf(maxDic_Code)+1));
		/*List<Object> maxModelIdList = loopList(queryModelIdList);
		List<Object> maxModelIdList = null;
		String maxModelId=null;
		String dicCode=null;
		String dispOrder=null;*/
		//if(maxModelIdList.isEmpty()||maxModelIdList==null){
		//String maxModelId="0";
		String dicCode="00";
		String dispOrder="0";
		/*}else{
			maxModelId=(String) maxModelIdList.get(0);//得到最大的DISP_ORDER
			dicCode="0"+(Integer.parseInt(maxModelId)+1);
			dispOrder=(Integer.parseInt(maxModelId)+1)+"";
		}*/
		String insertSql="insert into TBL_DICTIONARYLAYERITEM values(?,?,?,?,?,?,?,?)";
		String dicType="TMNL_MODEL_NO";
		
		String dicPcode=dicCode0;
		String dicLevel="0";
		
		String name=termVer.getModelId();
		String memo="终端型号";
		Date updateTime=new Date();
		List<Object> list=new ArrayList<Object>();
		list.add(dicType);
		list.add(dicCode);
		list.add(dicPcode);
		list.add(dicLevel);
		list.add(dispOrder);
		list.add(name);
		list.add(memo);
		list.add(updateTime);
		sqlBaseDao.deleteBySql(insertSql, list);
		
	}
	
	
	
	/**
	 * 查询存在该厂商时型号表里Dic_Code的最大值
	 * @param termVer
	 * @throws DaoException 
	 */
	private String queryMaxDicCode(List<Object> queryManufacturerList) throws DaoException {
		String querySql="SELECT MAX(DISP_ORDER) FROM TBL_DICTIONARYLAYERITEM T  WHERE DIC_TYPE = 'TMNL_MODEL_NO' and DIC_PCODE=? ";
		
		Object[] param={queryManufacturerList.get(0)};
		List<Object> queryList = pageDao.querySqlAll(querySql, param);
		String maxDic_Code=String.valueOf(queryList.get(0));
		return maxDic_Code;
	}
	
	
	/**
	 * 添加已存在厂商的型号
	 * @param termVer
	 * @return
	 * @throws DaoException 
	 */
	private void insertModelId2(TermVer termVer,String maxDic_Code,List<Object> queryManufacturerList) throws DaoException {
		String dicCode0=(String) queryManufacturerList.get(0);//上一级厂商的diccode  List<Object> queryModelIdList
		String maxModelId=null;
		String dicCode=null;
		String dispOrder=null;
		if(queryManufacturerList.isEmpty()||queryManufacturerList==null){
			maxModelId="0";
			dicCode="00";
			dispOrder="0";
		}else{
			maxModelId=maxDic_Code;//得到最大的DISP_ORDER
			if((Integer.parseInt(maxModelId)+1)>9){
				dicCode=(Integer.parseInt(maxModelId)+1)+"";
				dispOrder=(Integer.parseInt(maxModelId)+1)+"";
			}else{
			dicCode="0"+(Integer.parseInt(maxModelId)+1);
			dispOrder=(Integer.parseInt(maxModelId)+1)+"";
			}
		}
		String insertSql="insert into TBL_DICTIONARYLAYERITEM values(?,?,?,?,?,?,?,?)";
		String dicType="TMNL_MODEL_NO";
		
		String dicPcode=dicCode0;
		String dicLevel="0";
		
		String name=termVer.getModelId();
		String memo="终端型号";
		Date updateTime=new Date();
		List<Object> list=new ArrayList<Object>();
		list.add(dicType);
		list.add(dicCode);
		list.add(dicPcode);
		list.add(dicLevel);
		list.add(dispOrder);
		list.add(name);
		list.add(memo);
		list.add(updateTime);
		sqlBaseDao.deleteBySql(insertSql, list);
		
	}
	/**
	 * 添加到新表里
	 * @param termVer
	 * @param op
	 * @throws DaoException
	 */
	private void insertTermVer(TermVer termVer,Operators op) throws DaoException {
		TermVer termVerTbl = new TermVer();
		termVerTbl.setManufacturer(termVer.getManufacturer());
		termVerTbl.setModelId(termVer.getModelId());
		termVerTbl.setVersionId(termVer.getVersionId());
		termVerTbl.setIssueTs(termVer.getIssueTs());
		termVerTbl.setIsValId(termVer.getIsValId());
		termVerTbl.setOpId(String.valueOf(op.getId()));
		termVerTbl.setRecCteTs(new Date());
		termVerTbl.setOperIn("I");
		baseDao.editSave(termVerTbl);
	}
	
	
	private void updateTermVer(TermVer termVer, Operators op) throws DaoException {
		String updateSql="update T_TERM_VER set VERSION_ID=?,ISSUE_TS=?, IS_VALID=?,OP_ID=? ,REC_UDP_TS=?, OPER_IN=? where id=?";
		List<Object> list=new ArrayList<Object>();
		list.add(termVer.getVersionId());
		list.add(termVer.getIssueTs());
		list.add(termVer.getIsValId());
		list.add(String.valueOf(op.getId()));
		list.add(new Date());
		list.add("U");
		list.add(termVer.getId());
		sqlBaseDao.deleteBySql(updateSql, list);
	}


	/**
	 * 遍历查询到的list
	 * @param querylist
	 * @return
	 */
	private List<Object> loopList(List<Object> querylist){
		ArrayList<Object> arrayList = new ArrayList<Object>();
		if(!querylist.isEmpty()){
			for(Object obj:querylist){
				Object[] ob = (Object[])obj;
				arrayList.add(ob[0]);
				//arrayList.add(ob[1]);
			}
			return arrayList;
		}else{
			return querylist;
		}
		
	}

	private void deleteTermVer(TermVer termVer) throws DaoException {
		String deleteSql="delete from T_TERM_VER where id=?";
		List<Object> list=new ArrayList<Object>();
		list.add(termVer.getId());
		sqlBaseDao.deleteBySql(deleteSql, list);
	}


}
